/**
 * @fileOverview The "indydialogui" plugin.
 */
VED.plugins.add( 'indydialogui', {
   onLoad: function() {

      var initPrivateObject = function( elementDefinition ) {
            this._ || ( this._ = {} );
            this._[ 'default' ] = this._.initValue = elementDefinition[ 'default' ] || '';
            this._.required = elementDefinition[ 'required' ] || false;
            var args = [ this._ ];
            for ( var i = 1; i < arguments.length; i++ )
               args.push( arguments[ i ] );
            args.push( true );
            VED.tools.extend.apply( VED.tools, args );
            return this._;
         },
         commonBuilder = {
            build: function( dialog, elementDefinition, output ) {
               return new VED.ui.dialog[ elementDefinition.type ]( dialog, elementDefinition, output );
            }
         },
         commonPrototype = {
            isChanged: function() {
               return this.getValue() != this.getInitValue();
            },

            reset: function( noChangeEvent ) {
               this.setValue( this.getInitValue(), noChangeEvent );
            },

            setInitValue: function() {
               this._.initValue = this.getValue();
            },

            resetInitValue: function() {
               this._.initValue = this._[ 'default' ];
            },

            getInitValue: function() {
               return this._.initValue;
            }
         },
         commonEventProcessors = VED.tools.extend( {}, VED.ui.dialog.uiElement.prototype.eventProcessors, {
            onChange: function( dialog, func ) {
               if ( !this._.domOnChangeRegistered ) {
                  dialog.on( 'load', function() {
                     this.getInputElement().on( 'change', function() {
                        // Make sure 'onchange' doesn't get fired after dialog closed. (#5719)
                        if ( !dialog.parts.dialog.isVisible() )
                           return;

                        this.fire( 'change', { value: this.getValue() } );
                     }, this );
                  }, this );
                  this._.domOnChangeRegistered = true;
               }

               this.on( 'change', func );
            }
         }, true ),
         eventRegex = /^on([A-Z]\w+)/,
         cleanInnerDefinition = function( def ) {
            // An inner UI element should not have the parent's type, title or events.
            for ( var i in def ) {
               if ( eventRegex.test( i ) || i == 'title' || i == 'type' )
                  delete def[ i ];
            }
            return def;
         };

      VED.tools.extend( VED.ui.dialog, {
         
         ajaxText: function( dialog, elementDefinition, htmlList ) {
            if ( arguments.length < 3 )
               return;

            initPrivateObject.call( this, elementDefinition );
            var domId = this._.inputId = VED.tools.getNextId() + '_ajaxText',
               attributes = { 'class': 'ved_dialog_ui_input_' + elementDefinition.type, id: domId, type: elementDefinition.type },
               i;

            // Set the validator, if any.
            if ( elementDefinition.validate )
               this.validate = elementDefinition.validate;

            // Set the max length and size.
            if ( elementDefinition.maxLength )
               attributes.maxlength = elementDefinition.maxLength;
            if ( elementDefinition.size )
               attributes.size = elementDefinition.size;

            if ( elementDefinition.inputStyle )
               attributes.style = elementDefinition.inputStyle;

            // If user presses Enter in a text box, it implies clicking OK for the dialog.
            var me = this,
               keyPressedOnMe = false;
            dialog.on( 'load', function() {
               me.getInputElement().on( 'keydown', function( evt ) {
                  if ( evt.data.getKeystroke() == 13 )
                     keyPressedOnMe = true;
               });

               // Lower the priority this 'keyup' since 'ok' will close the dialog.(#3749)
               me.getInputElement().on( 'keyup', function( evt ) {
                  if ( evt.data.getKeystroke() == 13 && keyPressedOnMe ) {
                     dialog.getButton( 'ok' ) && setTimeout( function() {
                        dialog.getButton( 'ok' ).click();
                     }, 0 );
                     keyPressedOnMe = false;
                  }
               }, null, null, 1000 );
            });

            var innerHTML = function() {
                  // IE BUG: Text input fields in IE at 100% would exceed a <td> or inline
                  // container's width, so need to wrap it inside a <div>.
                  var html = [ '<div class="ved_dialog_ui_input_', elementDefinition.type, '" role="presentation"' ];

                  if ( elementDefinition.width )
                     html.push( 'style="width:' + elementDefinition.width + '" ' );

                  html.push( '><input ' );

                  attributes[ 'aria-labelledby' ] = this._.labelId;
                  this._.required && ( attributes[ 'aria-required' ] = this._.required );
                  for ( var i in attributes )
                     html.push( i + '="' + attributes[ i ] + '" ' );
                  html.push( ' /></div>' );
                  return html.join( '' );
               };
            VED.ui.dialog.labeledElement.call( this, dialog, elementDefinition, htmlList, innerHTML );
            
         }
         
      }, true );

      /** @class VED.ui.dialog.ajaxText */
      VED.ui.dialog.ajaxText.prototype = VED.tools.extend( new VED.ui.dialog.labeledElement, {

      /*
         getInputElement: function() {
            return this._.select.getElement();
         },

         getTextElement: function() {
            return this._.text.getElement();
         },

         add: function( label, value, index ) {
            var option = new VED.dom.element( 'option', this.getDialog().getParentEditor().document ),
               selectElement = this.getInputElement().$;
            option.$.text = label;
            option.$.value = ( value === undefined || value === null ) ? label : value;
            if ( index === undefined || index === null ) {
               if ( VED.env.ie )
                  selectElement.add( option.$ );
               else
                  selectElement.add( option.$, null );
            } else
               selectElement.add( option.$, index );
            return this;
         },

         remove: function( index ) {
            var selectElement = this.getInputElement().$;
            selectElement.remove( index );
            return this;
         },

         clear: function() {
            var selectElement = this.getInputElement().$;
            while ( selectElement.length > 0 )
               selectElement.remove( 0 );
            return this;
         },
         
         eventProcessors: VED.tools.extend( {}, VED.ui.dialog.uiElement.prototype.eventProcessors, {
            onChange: function( dialog, func ) {
               dialog.on( 'load', function() {
                  var text_el   = this.getTextElement(),
                      select_el = this.getInputElement(),
                      options = select_el.getChildren(),
                      count = options.count(),
                      i;

                  select_el.on('change', function(evt) {
                     console.log(this);
                  });
                  
                  text_el.on('keyup', function(evt) {
                     var text = text_el.getValue().ltrim(),
                         reg = new RegExp( text, 'i' ),
                         matched = [];

                     if( text ) {
                        for( i=0; i<count; i++  ) {
                           var option = options.getItem(i);
                           if( option.getText().ltrim().search(reg) === 0 ) {
                              matched.push({ id:option.getValue(), text: option.getText().ltrim() });
                           }
                        }
                        
                        if( matched.length == 1 ) {
                           text_el.setValue( matched[0].text );
                           select_el.setValue( matched[0].id );
                        } else if( matched.length > 1 ) {
                           text_el.setValue( matched[0].text );
                           text_el.$.selectionStart = text.length;
                           text_el.$.selectionEnd   = matched[0].text.length;
                           select_el.setValue( matched[0].id );
                           
                        } else {
                           select_el.setValue('');
                        }
                        
                        // console.log( matched );
                     }
                     
                     
                  });


               }, this );
               this.on( 'change', func );
               
               return null;
            }
         }, true ),
*/

         keyboardFocusable: true
      }, commonPrototype, true );

      VED.dialog.addUIElement( 'ajaxText', commonBuilder );
   }
});






